import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '../utils/request'

export const useCartStore = defineStore('cart', () => {
  const cartItems = ref([])
  
  const total = computed(() => {
    return cartItems.value.reduce((sum, item) => sum + item.price * item.count, 0)
  })

  const totalCount = computed(() => {
    return cartItems.value.reduce((sum, item) => sum + item.count, 0)
  })

  async function getCartList() {
    try {
      const list = await request({
        url: "/ShopCountInfo"
      })
      console.log("cartList:", list)
      cartItems.value = list
    } catch (error) {
      console.error('获取购物车列表失败:', error)
    }
  }

  async function updateItemCount(id, count) {
    try {
      const flag = await request({
        url: "/updateItemCount",
        params: { id, count }
      })
      if (flag === "success") {
        const item = cartItems.value.find(item => item.id === id)
        if (item) {
          item.count = count
        }
      }
    } catch (error) {
      console.error('更新商品数量失败:', error)
    }
  }

  function addToCart(item) {
    const existing = cartItems.value.find(i => i.id === item.id)
    if (existing) {
      existing.count++
    } else {
      cartItems.value.push({ ...item, count: 1 })
    }
  }

  function removeFromCart(itemId) {
    const index = cartItems.value.findIndex(item => item.id === itemId)
    if (index > -1) {
      cartItems.value.splice(index, 1)
    }
  }

  return {
    cartItems,
    total,
    totalCount,
    getCartList,
    updateItemCount,
    addToCart,
    removeFromCart
  }
}) 